package com.cz.run.wechat;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.Product;
import com.cz.run.beans.mysql.UserExtWechatProfile;
import com.cz.run.beans.mysql.UserForceDynamic;
import com.cz.run.beans.mysql.UserReferral;
import com.cz.run.beans.vo.product.ProductVO;
import com.cz.run.bumng.model.*;
import com.cz.run.service.IProductService;
import com.cz.run.service.IUserExtWechatProfileService;
import com.cz.run.service.IUserForceDynamicService;
import com.cz.run.service.IUserReferralService;
import com.cz.run.utils.DateUtil;
import com.cz.run.utils.WXUtils;
import com.cz.run.utils.WxUtils2;
import com.cz.run.wechat.model.WechatInfoModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小程序
 * Created by deior on 2018/6/10.
 */
@Api(value = "小程序")
@Controller
@RequestMapping("/wechat")
public class SmallProgram {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IUserExtWechatProfileService iUserExtWechatProfileService;

    @Autowired
    private IUserForceDynamicService userForceDynamicService;

    @Autowired
    private IUserReferralService iUserReferralService;

    @Autowired
    private IProductService productService;

    private static final String appId = "wx69e4017a71d7d3ed";
    private static final String secret = "950b461087a54ca8c15000be5cc09534";

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SmallProgram.class);

    @ApiOperation(value = "获取授权信息", notes = "获取授权信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping("/getInfo")
    @ResponseBody
    public Object getCode(HttpServletRequest request){

        String code = request.getParameter("code");
        if(StringUtils.isEmpty(code)){
            return  new Result(false,"code为空");
        }

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}" +
                "&js_code={js_code}&grant_type=authorization_code";

        //要让 MappingJackson2HttpMessageConverter 能处理头部 Content-Type 为 text/plain 类型的 Json 返回值
        //继承 MappingJackson2HttpMessageConverter 并在构造过程中设置其支持的 MediaType 类型
        //WxMappingJackson2HttpMessageConverter 追加到 RestTemplate 的 messageConverters 消息转换链中
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());

        com.cz.run.wechat.model.WechatInfo wechatInfo = (com.cz.run.wechat.model.WechatInfo) request.getSession().getAttribute(code);
        if(null==wechatInfo) {
            //post json数据

            Map<String, String> params = new HashMap<>();
            params.put("data", "request for post");
            params.put("appId", appId);
            params.put("secret", secret);
            params.put("js_code", code);
            wechatInfo = restTemplate.getForObject(url,  com.cz.run.wechat.model.WechatInfo.class,params);

            if(null == wechatInfo || !wechatInfo.valid()){
                logger.error("getBaseUserInfo invalid: " + wechatInfo);
                wechatInfo = null;
            }
            request.getSession().setAttribute(code,wechatInfo);
        }

    return  wechatInfo;
    }
    public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
        public WxMappingJackson2HttpMessageConverter(){
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.TEXT_PLAIN);
            setSupportedMediaTypes(mediaTypes);
        }
    }

    @ApiOperation(value = "上传微信信息", notes = "上传微信信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping("/addWechatInfo")
    @ResponseBody
    public Object getCode(@RequestBody UserExtWechatProfile userExtWechatProfile, HttpServletRequest request){

        if(StringUtils.isEmpty(userExtWechatProfile.getUnionid())){
            return new Result(false,"unionid不能为空");
        }

        if(StringUtils.isEmpty(userExtWechatProfile.getOpenidMobile())){
            return new Result(false,"sessionKey不能为空");
        }

        if(StringUtils.isEmpty(userExtWechatProfile.getOpenidWeb())){
            return new Result(false,"iv不能为空");
        }

        WechatUserInfoModel wechatUserInfoModel = WxUtils2.getUserInfo(userExtWechatProfile.getUnionid(),userExtWechatProfile.getOpenidMobile(),userExtWechatProfile.getOpenidWeb());
        if(null==wechatUserInfoModel||StringUtils.hasLength(wechatUserInfoModel.getUnionid())||StringUtils.hasLength(wechatUserInfoModel.getWatermark())){
            return new Result(false,"数据为空");
        }

        EntityWrapper<UserExtWechatProfile> ew = new EntityWrapper<>();
        ew.where("unionid = {0}",wechatUserInfoModel.getUnionid());
        UserExtWechatProfile userExtWechatProfile1 =iUserExtWechatProfileService.selectOne(ew);
        if(null==userExtWechatProfile1){
            if(null==userExtWechatProfile.getUserId()){
                return new Result(false,"211");
            }
            userExtWechatProfile.setUnionid(wechatUserInfoModel.getUnionid());
            iUserExtWechatProfileService.insert(userExtWechatProfile);

            EntityWrapper<UserReferral> reew = new EntityWrapper<>();
            reew.where("user_id={0}",userExtWechatProfile.getUserId());
            UserReferral userReferral=iUserReferralService.selectOne(reew);
            return new Result(true,new WechatInfoModel(userExtWechatProfile.getUserId(),userReferral.getCode()));
        }

        EntityWrapper<UserReferral> reew = new EntityWrapper<>();
        reew.where("user_id={0}",userExtWechatProfile1.getUserId());
        UserReferral userReferral=iUserReferralService.selectOne(reew);
        return new Result(true,new WechatInfoModel(userExtWechatProfile1.getUserId(),userReferral.getCode()));
    }

    @ApiOperation(value = "商品列表", notes = "商品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/list")
    @ResponseBody
    public ReturnDTO<PageDTO<ProductVO>> list(@RequestBody PageDTO pageDTO) throws Exception {
        Page<Product> page = new Page<>(pageDTO.getCurrentPage(), pageDTO.getPageSize());
        page = productService.selectPage(page);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            List<ProductVO> list = new ArrayList<>();
            ProductVO vo = null;
            for (Product product : page.getRecords()) {
                vo = new ProductVO();
                BeanUtils.copyProperties(product, vo);
                list.add(vo);
            }
            pageDTO.setContent(list);
        }
        pageDTO.setTotalRecord(page.getTotal());
        return ReturnDTO.success(pageDTO);
    }

    @ResponseBody
    @ApiOperation(value = "更新步数", notes = "更新步数", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "putStopNum")
    public Object putStopNum(@RequestBody WechatInfo wechatInfo, HttpServletRequest request) throws Exception {
        if(null==wechatInfo||StringUtils.isEmpty(wechatInfo.getEncryptedData())||StringUtils.isEmpty(wechatInfo.getSessionKey())||StringUtils.isEmpty(wechatInfo.getIv())){
            return new Result(false,"参数为空");
        }

        EntityWrapper<UserForceDynamic> uf = new EntityWrapper<>();
        uf.where("user_id = {0}", wechatInfo.getUserId());
        uf.and("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), 0));
        UserForceDynamic userForceDynamic = userForceDynamicService.selectOne(uf);
        WeRun weRun = WXUtils.getUserInfo(wechatInfo.getEncryptedData(),wechatInfo.getSessionKey(),wechatInfo.getIv());
        if(null==weRun){
            return new Result(false,"步数数据为空");
        }

        Map<Long,Integer> map =new HashMap<>();
        for(StepInfo stepInfo:weRun.getStepInfoList()){
            map.put(stepInfo.getTimestamp(),stepInfo.getStep());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (userForceDynamic != null) {

            userForceDynamic.setStep(map.get(format.parse(DateUtil.currentTimeMillisCN3(new Date())+" 00:00:00").getTime()/1000));
            userForceDynamicService.updateById(userForceDynamic);
        } else {
            userForceDynamic = new UserForceDynamic();
            userForceDynamic.setStep( map.get(format.parse(DateUtil.currentTimeMillisCN3(new Date())+" 00:00:00").getTime()/1000));
            userForceDynamic.setTime(new Date());
            userForceDynamic.setUserId(Integer.parseInt(wechatInfo.getUserId()));
            userForceDynamicService.insert(userForceDynamic);
        }
        return ReturnDTO.success(userForceDynamic.getStep());
    }
    public static void main(String [] args) throws ParseException {
       // System.out.print(new Date(1526054400));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.print(format.parse(DateUtil.currentTimeMillisCN3(new Date())+" 00:00:00").getTime()/1000);
    }



}
